<template>
  <view class="page">
    <!-- <bar-title
      @rightTap="deleteCard"
      :bgColor="`background-color:#ffffff;color:#333333`"
      :isBack="false"
    >
      <block slot="left">
        <image
          src="http://cdn.gtfy.net.cn/1inex/bank/left_arrow.svg"
          class="left-arrow-icon"
          mode="scaleToFill"
          @click="back"
        />
      </block>

      <block slot="right">删除</block>
    </bar-title> -->

    <Head @rightClick="deleteCard">
      <text slot="right">删除</text>
    </Head>

    <view class="bank-title">
      <view class="main">{{ mode === "edit" ? "修改" : "添加" }}银行卡</view>
      <view class="sub">
        <image
          src="http://cdn.gtfy.net.cn/1inex/bank/dunpai.svg"
          mode="scaleToFill"
        />
        <text>中安晟鼎全力保护你的信息安全</text>
      </view>
    </view>
    <!-- 表单 -->
    <form @submit="submitData">
      <view class="add-card-form">
        <view class="list">
          <view class="left">姓名 </view>
          <view class="right">
            <input
              type="text"
              placeholder="请填写姓名"
              v-model="userobj.realName"
              name="realName"
            />
          </view>
        </view>
        <view class="list">
          <view class="left">银行 </view>
          <view class="right">
            <input
              type="text"
              placeholder="请填写银行"
              v-model="userobj.bankName"
              name="bankName"
            />
          </view>
        </view>

        <view class="list">
          <view class="left">开户行 </view>
          <view class="right">
            <input
              type="text"
              placeholder="请填写开户行"
              v-model="userobj.bankAddress"
              name="bankAddress"
            />
          </view>
        </view>

        <view class="list">
          <view class="left">银行卡号 </view>
          <view class="right">
            <input
              type="text"
              placeholder="请填写银行卡号"
              v-model="userobj.bankNo"
              name="bankNo"
            />
          </view>
        </view>
        <view class="list">
          <view class="left">身份证号 </view>
          <view class="right">
            <input
              type="text"
              placeholder="请填写身份证号"
              v-model="userobj.idCard"
              name="idCard"
            />
          </view>
        </view>
      </view>

      <view class="foot">
        <!-- <view class="but" @click="add"> 确定 </view> -->
        <button
          :class="canSubmit ? 'but-active' : 'but'"
          formType="submit"
        >
          {{ mode === "edit" ? "修改保存" : "确定" }}
        </button>
        <!-- <button class="but-del" formType="submit">删除</button> -->
      </view>
    </form>
    <!-- <pcaPicker ref="pcaPicker" @confirm="getPCA"></pcaPicker> -->
  </view>
</template>

<script>
import { userInfoAPI } from "@/api/login.js";
import WxValidate from "@/common/WxValidate.js";
import { bankAdd, bankEdit, updateUserDataAPI } from "@/api/bank.js";
import Head from "@/components/Head/index";
export default {
  components: {
    Head,
  },
  data() {
    return {
      userobj: {
        idCard: "",
        realName: "",
        bankNo: "",
        bankName: "",
        bankAddress: "",
      },
      typeText: "店铺",
      bank: "",
      array: [{ title: "上饶银行" }],
      bank: "",
      index: 0,
      piv: "",
      imgArr: [],
      mode: "add",
      id: "",
    };
  },
  filters: {
    b(val) {
      if (val == "") {
        return "请选择";
      } else {
        return val;
      }
    },
  },
  computed: {
    canSubmit() {
      if (this.userobj.idCard && this.userobj.realName && this.userobj.bankNo && this.userobj.bankName) {
        return true;
      }

      return false;
    },
  },
  onLoad(option) {
    if (option.mode === "edit") {
      this.mode = "edit";
      console.log("edit mode");
      this.getBankInfo();
    } else {
      this.getinfo();
    }
    this.initValidata();
  },
  methods: {
    back() {
      uni.navigateBack();
    },
    /**
     * 删除卡
     */
    deleteCard() {
      const _this = this;

      uni.showModal({
        title: "删除",
        content: "确认删除该银行卡吗?",
        success({ confirm }) {
          if (confirm) {
            // 编辑模式
            bankEdit({ ..._this.userobj, id: _this.id, status: 2 }).then((res) => {
              if (res.code === 200) {
                uni.showToast({
                  title: "删除成功",
                  icon: "none",
                  mask: true,
                });

                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              }
            });
          }
        },
      });
    },
    getBankInfo() {
      try {
        let editBank = JSON.parse(uni.getStorageSync("editBank"));
        console.log("%c [ editBank ]-86", "font-size:13px; background:#333333; color:#f3f3f3;", editBank);
        this.userobj = {
          realName: editBank.realName,
          bankName: editBank.bankName,
          idCard: editBank.idCard,
          bankNo: editBank.bankNo,
          bankAddress: editBank.bankAddress,
        };

        this.id = editBank.id;
      } catch (error) {
        uni.showToast({
          title: "发生错误",
          icon: "none",
          mask: true,
        });
      }
    },
    /**
     * 初始化校验规则
     */
    initValidata() {
      const rules = {
        realName: {
          required: true,
        },
        bankName: {
          required: true,
        },
        bankAddress: {
          required: true,
        },
        bankNo: {
          required: true,
          bankNoRight: true,
        },
        idCard: {
          required: true,
          idcard: true,
        },
      };
      const messages = {
        realName: {
          required: "请输入姓名",
        },
        bankName: {
          required: "请输入银行名",
        },
        bankAddress: {
          required: "请输入开户行",
        },
        bankNo: {
          required: "请设置正确银行卡号",
        },
        idCard: {
          required: "请输入数量",
          idcard: "请输入正确的身份证",
        },
      };

      this.WxValidate = new WxValidate(rules, messages);
      this.WxValidate.addMethod(
        "bankNoRight",
        (value) => {
          let regex1 = /^([1-9]{1})(\d{11}|\d{15}|\d{16}|\d{17}|\d{18})$/;
          let regex2 = /^([1-9]{1})(\d{15}|\d{16}|\d{18})$/;

          if (regex1.test(value) || regex2.test(value)) {
            return true;
          }
          return false;
        },
        "请输入正确银行卡号"
      );
    },
    // 获取缓存的用户信息
    getinfo() {
      let userData;
      try {
        userData = JSON.parse(uni.getStorageSync("addressData"));
      } catch (error) {
        userData = false;
      }
      if (userData) {
        this.$set(this.userobj, "realName", userData.realName);
        this.$set(this.userobj, "idCard", userData.idCard);
      } else {
        userInfoAPI().then((res) => {
          this.$set(this.userobj, "realName", res.realName);
          this.$set(this.userobj, "idCard", res.idCard);
        });
      }
    },

    bindPickerChange: function (e) {
      console.log("picker发送选择改变，携带值为：" + e.detail.value);
      this.bank = this.array[e.detail.value].title;
    },
    /**
     * 新版添加银行卡
     */
    submitData(e) {
      let params = e.detail.value;
      console.log("%c [ params ]-264", "font-size:13px; background:#333333; color:#f3f3f3;", params);
      if (!this.WxValidate.checkForm(params)) {
        const error = this.WxValidate.errorList[0];
        // 可以自定义提示
        uni.showToast({
          title: `${error.msg}`,
          icon: "none",
        });
        return false;
      } else {
        if (this.mode === "edit") {
          // 编辑模式
          bankEdit({ ...params, id: this.id, status: 1 }).then((res) => {
            if (res.code === 200) {
              uni.showToast({
                title: res.msg,
                icon: "none",
                mask: true,
              });

              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
          });
        } else {
          // 新增模式
          bankAdd(params).then((res) => {
            console.log(res);
            if (res.code === 200) {
              uni.showToast({
                title: res.msg,
                icon: "none",
                mask: true,
              });

              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
          });
        }
      }
    },
    /**
     * 老版添加银行卡,已弃用
     */
    add() {
      let validateBankCard = /^([1-9]{1})(\d{14}|\d{18})$/;
      if (!this.userobj.bankNo) {
        uni.showToast({
          title: "请填写卡号",
          icon: "none",
        });
        return;
      }
      if (!validateBankCard.test(this.userobj.bankNo)) {
        uni.showToast({
          title: "请填写正确卡号",
          icon: "none",
        });
        return;
      }
      let reg2 = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if (!reg2.test(this.userobj.idCard)) {
        uni.showToast({
          title: "请填写正确身份证号",
          icon: "none",
        });
        return;
      }
      if (!this.userobj.idCard) {
        uni.showToast({
          title: "请填写身份证号",
          icon: "none",
        });
        return;
      }
      let reg3 = /^[\u4e00-\u9fa5]{0,}$/;
      if (!reg3.test(this.userobj.realName)) {
        uni.showToast({
          title: "姓名格式有误",
          icon: "none",
        });
        return;
      }
      if (!this.userobj.realName) {
        uni.showToast({
          title: "请填写姓名",
          icon: "none",
        });
        return;
      }
      if (!reg3.test(this.userobj.bankName)) {
        uni.showToast({
          title: "开户行格式有误",
          icon: "none",
        });
        return;
      }
      if (!this.userobj.bankName) {
        uni.showToast({
          title: "请填写开户行",
          icon: "none",
        });
        return;
      }
      var data = {
        realName: this.userobj.realName,
        idCard: this.userobj.idCard,
        bankName: this.userobj.bankName,
        bankNo: this.userobj.bankNo,
      };
      updateUserDataAPI(data).then((res) => {
        uni.showToast({
          title: "提交成功",
        });
        //uni.navigateBack();
        uni.navigateTo({
          url: "/pages/my/bankCard",
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 20rpx;
  background-color: #f6f6f6;
  min-height: 100vh;
}

.left-arrow-icon {
  width: 20rpx;
  height: 36rpx;
  margin-left: 10rpx;
}

.bank-title {
  width: 100%;
  height: 200rpx;

  box-sizing: border-box;
  padding: 50rpx 0;

  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: center;

  .main {
    width: 100%;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 40rpx;
    font-family: "Microsoft YaHei", 微软雅黑, "MicrosoftJhengHei", 华文细黑, STHeiti, MingLiu;
    font-weight: bold;
    color: #333333;
    text-align: center;
  }

  .sub {
    width: 100%;
    height: 24rpx;
    font-size: 24rpx;
    line-height: 24rpx;

    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;

    font-family: "Microsoft YaHei", 微软雅黑, "MicrosoftJhengHei", 华文细黑, STHeiti, MingLiu;
    font-weight: bold;
    color: #333333;

    image {
      width: 22rpx;
      height: 24rpx;
      margin-right: 10rpx;
    }
  }
}

.add-card-form {
  width: 750rpx;
  min-height: 791rpx;
  background: #ffffff;

  box-sizing: border-box;
  padding: 40rpx;

  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: center;

  .list {
    background-color: #fff;
    height: 150rpx;
    display: flex;
    align-items: center;

    justify-content: space-between;
    font-size: 30rpx;

    display: flex;
    flex-flow: column nowrap;
    justify-content: space-between;
    align-items: flex-start;

    .left {
      width: 100%;
      height: 24rpx;
      font-size: 24rpx;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #666666;

      margin-bottom: 20rpx;
    }

    .right {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #666666;

      input {
        width: 630rpx;
        height: 100rpx;
        background: #f7f7f7;
        border-radius: 50rpx;
        text-align: left;
        font-size: 28rpx;

        box-sizing: border-box;
        padding: 0 40rpx;
      }
    }
  }
}

.foot {
  width: 100%;
  min-height: 100rpx;
  margin-top: 30rpx;
  display: flex;
  align-items: center;

  display: flex;
  flex-flow: column nowrap;
  justify-content: space-evenly;
  align-items: center;

  .but {
    background: #d3d3d3;
    background-size: cover;
    margin: 0 auto;

    width: 630rpx;
    height: 100rpx;
    border-radius: 50rpx;

    font-size: 36rpx;
    line-height: 100rpx;
    font-weight: 400;
    text-align: center;
    color: #fff;
  }

  .but-active {
    background: linear-gradient(-15deg, $price 0%, #ff5b50 100%);

    background-size: cover;
    margin: 0 auto;

    width: 630rpx;
    height: 100rpx;
    border-radius: 50rpx;

    font-size: 36rpx;
    line-height: 100rpx;
    font-weight: 400;
    text-align: center;
    color: #fff;
  }
}
</style>
